'''
Created on 22/07/2010

@author: eh01
'''
from runtime.service import Service
from datastore.uri import Uri
from datastore.resource import Resource
from datastore.spaces import Spaces
from spear.a2p_service import A2PServiceAPI

class AdaptorAdminService(Service):

    OPERATION = "operation"
    RAS = "ras"
    USERS = "users"
    RESPONSE = 'response'
    SPEAR_ADAPTOR_ADMINISTRATION_HEADER = "SPEAR Adaptor Administration"
    VIEW_SPEAR_CONNECTION_STATUS_HEADER = "View SPEAR Connection Status"
    REFRESH_RA_AND_USER_LIST_HEADER = "Refresh RA and User List"
    VIEW_SPEAR_CPS_INTERACTION_ACTIVITY_HEADER = "View SPEAR/CPS Interaction Activity"
    CONFIGURE_SPEAR_ADAPTOR_HEADER = "Configure SPEAR Adaptor"
    CONNECTION_SUCCESSFUL = 'Connection successful'
    REFRESH_SUCCESSFUL = 'Refresh successful'
    REFRESH_FAILED = 'Refresh failed'
    CONFIGURATIONS_SAVED = 'Configurations Saved. Please restart node for changes to take effect.'
    SPEAR_USERNAME = 'spear_username'
    SPEAR_PASSWORD = 'spear_password'
    SPEAR_HOSTNAME = 'spear_hostname'

    def cb_start(self, uri, action, res):      
        self.spaces.set_process(Uri('external:adaptor/admin'), self.cb_admin_options)
        self.spaces.set_process(Uri('external:adaptor/admin/view-spear-connection-status'), self.cb_view_spear_connection_status_get)
        self.spaces.set_process(Uri('external:adaptor/admin/refresh-ra-and-user-list'), self.cb_refresh_ra_and_user_list_get)
        self.spaces.set_process(Uri('internal:adaptor/admin/refresh-ra-and-user-list/'), self.cb_refresh_ra_and_user_list_post)
        self.spaces.set_process(Uri('external:adaptor/admin/view-spear-cps-interaction-activity'), self.cb_view_spear_cps_interaction_activity)
        self.spaces.set_process(Uri('external:adaptor/admin/configure-spear-adaptor'), self.cb_configure_spear_adaptor_get)
        self.spaces.set_process(Uri('internal:adaptor/admin/configure-spear-adaptor/'), self.cb_configure_spear_adaptor_post)        
        
    def cb_admin_options(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            res = Resource(type="term:eplanning/adaptor/admin/get/data")
            res.h1_header = AdaptorAdminService.SPEAR_ADAPTOR_ADMINISTRATION_HEADER
            return res
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            return
        
    def cb_view_spear_connection_status_get(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            rs = self.spaces.get(Uri("internal:eplanning/spear/a2pspear_service/a2pspearstatus"))
            res = Resource(type="term:eplanning/adaptor/view-spear-connection-status/get/data")
            res.h1_header = AdaptorAdminService.VIEW_SPEAR_CONNECTION_STATUS_HEADER
            res.date = rs.date
            res.connection_up = rs.connection_up
            return res
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            return
        
    def cb_refresh_ra_and_user_list_get(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            res = Resource(type="term:eplanning/adaptor/refresh-ra-and-user-list/get/data")
            res.h1_header = AdaptorAdminService.REFRESH_RA_AND_USER_LIST_HEADER
            return res
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            return
        
    def cb_refresh_ra_and_user_list_post(self, uri, action, res):
        if uri.split()[-1] == AdaptorAdminService.RESPONSE:
            # we are not doing anything with the response so we can safely ignore it. 
            return        
        if action == Spaces.ACTION_PUT:
            ras = False
            users = False
            # get the form data
            form_data = {}
            for key in res.form_fields.keys():
                form_data[key] = str(res.form_fields[key])
            if AdaptorAdminService.RAS in form_data:
                ras = True
            if AdaptorAdminService.USERS in form_data:
                users = True
            
            error = False
            if ras:
                response_ras_rs = self.do_ra_list_update(self.spaces)
                # check we have a var called error and check it is not empty string
                if response_ras_rs.has_var('error') and response_ras_rs.error:
                    error = True
            if users:
                response_users_rs = self.do_user_list_update(self.spaces)
                # check we have a var called error and check it is not empty string
                if response_users_rs.has_var('error') and response_users_rs.error:
                    error = True
                
            res = Resource(type="term:eplanning/adaptor/refresh-ra-and-user-list/get/data")
            res.h1_header = AdaptorAdminService.REFRESH_RA_AND_USER_LIST_HEADER
            if error:
                res.error = AdaptorAdminService.REFRESH_FAILED
            else:   
                res.message = AdaptorAdminService.REFRESH_SUCCESSFUL
            response_uri = uri + AdaptorAdminService.RESPONSE
            self.spaces.put(response_uri, res)
            return response_uri
        elif action == Spaces.ACTION_EXISTS:
            return False
        else:
            return
    
    def cb_view_spear_cps_interaction_activity(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            log_entries_resource = self.spaces.get(Uri('internal:base/services/logger/logs'))
            res = Resource(type="term:eplanning/adaptor/view-spear-cps-interaction-activity/get/data")
            res.h1_header = AdaptorAdminService.VIEW_SPEAR_CPS_INTERACTION_ACTIVITY_HEADER
            res.log_entries = log_entries_resource.log_entries
            return res
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            return

    def cb_configure_spear_adaptor_get(self, uri, action, res):
        if action == Spaces.ACTION_GET:
            res = Resource(type="term:eplanning/adaptor/configure-spear-adaptor/get/data")
            res.h1_header = AdaptorAdminService.CONFIGURE_SPEAR_ADAPTOR_HEADER
            return res
        elif action == Spaces.ACTION_EXISTS:
            return True
        else:
            return
    
    def cb_configure_spear_adaptor_post(self, uri, action, res):
        if uri.split()[-1] == AdaptorAdminService.RESPONSE:
            # we are not doing anything with the response so we can safely ignore it. 
            return
        if action == Spaces.ACTION_PUT:
            # get the form data
            form_data = {}
            for key in res.form_fields.keys():
                form_data[key] = str(res.form_fields[key])
            service_url = Uri("internal:base/config/eplanning/spear/a2pspear_service")
            a2pspear_service_rs = self.spaces.get(service_url)
            service = a2pspear_service_rs.services['eplanning/spear/a2pspear_service']
            service.options.statics.spear_username = form_data[AdaptorAdminService.SPEAR_USERNAME] 
            service.options.statics.spear_password = form_data[AdaptorAdminService.SPEAR_PASSWORD]
            service.options.statics.hostname = form_data[AdaptorAdminService.SPEAR_HOSTNAME]
            self.spaces.put(service_url, a2pspear_service_rs)
            res = Resource(type="term:eplanning/adaptor/configure-spear-adaptor/get/data")
            res.h1_header = AdaptorAdminService.CONFIGURE_SPEAR_ADAPTOR_HEADER
            res.message = AdaptorAdminService.CONFIGURATIONS_SAVED
            response_uri = uri + AdaptorAdminService.RESPONSE
            self.spaces.put(response_uri, res)                        
            return response_uri
        elif action == Spaces.ACTION_EXISTS:
            return False
        else:
            return
    
    def do_ra_list_update(self, spaces):
        a2p_service_api = A2PServiceAPI(spaces)
        rs = a2p_service_api.get_ra_list_from_Spear()
        return rs
        
    def do_user_list_update(self, spaces):
        a2p_service_api = A2PServiceAPI(spaces)
        rs = a2p_service_api.get_user_list_from_Spear()
        return rs